# -*- coding: UTF-8 -*-

from urllib.request import build_opener, HTTPCookieProcessor, Request
from http.cookiejar import CookieJar
import io
import random
import json


def encode_data(data):
    try:
        return bytes(data, 'utf-8')
    except:
        return bytes(data)


def decode_data(data):
    return io.StringIO(data.read().decode('utf-8'))


class Service(object):
    _service = None

    def __init__(self, base_url, timeout):
        cookie_jar = CookieJar()
        opener = build_opener(HTTPCookieProcessor(cookie_jar))
        self._opener = opener

        self.base_url = base_url
        self.timeout = timeout

    def __call__(self, method, *args):
        return self._rpc_call(method, *args)

    def _rpc_call(self, method, *args):
        params = {
            'service': self._service,
            'method': method,
            'args': args
        }

        base_url = self.base_url
        timeout = self.timeout

        url = '/jsonrpc'
        full_url = base_url + url

        data = {
            "jsonrpc": "2.0",
            "method": "call",
            "params": params,
            "id": random.randint(0, 1000000000),
        }

        # print('data:', data)

        data_json = json.dumps(data)

        request = Request(url=full_url, data=encode_data(data_json))
        request.add_header('Content-Type', 'application/json')

        response = self._opener.open(request, timeout=timeout)
        # print('response:', response)

        data = json.load(decode_data(response))
        # print('response:', data)

        error = data.get('error')
        if error:
            print('error', error)
            raise error

        result = data.get('result')
        return result


# pass

# service: common, db, object
#     serveice = common
#       method: version, about, login, authenticate
#     serveice = db
#       method:
#         create_database,
#         duplicate_database,
#         drop,
#         dump
#         restore,
#         rename
#         change_admin_password,
#         migrate_databases
#         db_exist,
#         list
#         list_lang,
#         list_countries
#         server_version,
#         authenticate
#     serveice = object
#       method:
#         execute',
#         execute_kw,


def test_call_rpc(base_url, service, method, args):
    print(service, method, args)

    url = '/jsonrpc'
    full_url = base_url + url

    params = {
        'service': service,
        'method': method,
        'args': args
    }

    data = {
        "jsonrpc": "2.0",
        "method": "call",
        "params": params,
        "id": random.randint(0, 1000000000),
    }

    data_json = json.dumps(data)

    request = Request(url=full_url, data=encode_data(data_json))
    request.add_header('Content-Type', 'application/json')

    cookie_jar = CookieJar()
    opener = build_opener(HTTPCookieProcessor(cookie_jar))

    response = opener.open(request, timeout=50000)
    data = json.load(decode_data(response))

    error = data.get('error')
    if error:
        print('error', error)
        raise error

    result = data.get('result')
    return result
